import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getInfo } from '@/api/user'
import md5 from 'md5'
import common from '@/utils/common'
// import routerData from '@/test/testData/router.json'
const state = {
  token: getToken(),
  authRoutes: [],
  userInfo: {},
  // 存放节点下的数据
  nodeInfo: {},
}

const mutations = {
  // 用户token
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NODEINFO: (state, data) => {
    state.nodeInfo = data
  },
  // 动态配置用户界面
  SET_AUTHROUTES: (state, authRoutes) => {
    state.authRoutes = authRoutes
  },
  SET_USERINFO: (state, data) => {
    delete data.menus
    state.userInfo = data
  },
}

const actions = {
  login({ commit }, userInfo) {
    const { userName, password, orgId } = userInfo
    return new Promise((resolve, reject) => {
      login({
        userName: userName.trim(),
        password: common.addSalt(md5(password)),
        orgId,
        sysId: 1,
        type: 0,
      })
        .then((response) => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          setToken(data.token)
          resolve(data.orgDtos)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then((response) => {
          const { data } = response
          // 这里更新新用户信息，处理路由
          const { menus } = data
          commit('SET_AUTHROUTES', menus)
          commit('SET_USERINFO', data)
          resolve(menus)
        })
        .then(() => {
          reject()
        })
    })
  },
  logout({ commit }) {
    // , state, dispatch
    commit('SET_TOKEN', '')
    commit('SET_AUTHROUTES', [])
    removeToken()
  },
  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      commit('SET_TOKEN', '')
      commit('SET_AUTHROUTES', [])
      removeToken()
      resolve()
    })
  },
  setNode({ commit }, info) {
    commit('SET_NODEINFO', info)
  },
}

export default {
  namespaed: true,
  state,
  mutations,
  actions,
}
